package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author boqing
 * @date 2025-08-04
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private DeviceMapper deviceMapper;

   /* @Value("${alert.deviceMainTainerRole}")
    private String deviceMainTainerRole;
    @Value("${alert.managerRole}")
    private String managerRole;*/

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void alertFilter() {
        // 1.查询所有规则,判断是否为空
        long count = this.count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (count == 0) {
            return;
        }
        // 2.从redis中查询所有设备上报数据,并判空
        List<Object> deviceDataListObj = redisTemplate.opsForHash().values(Constants.IOT_DEVICE_LAST_DATA);
        if (CollectionUtils.isEmpty(deviceDataListObj)) {
            return;
        }
        // 3.解析上报数据 (将物模型从obj转deviceData)
        List<DeviceData> deviceDataList = new ArrayList<>();
        // 遍历每一个设备
        deviceDataListObj.forEach(deviceDataItem -> {
            // 将每一个设备上报数据的物模型数据转为list
            List<DeviceData> list = JSONUtil.toList(deviceDataItem.toString(), DeviceData.class);
            deviceDataList.addAll(list);
        });
        // 4.数据报警处理 (遍历每一个物模型数据)
        deviceDataList.forEach(deviceData -> {
            alertFilter(deviceData);
        });
    }

    /**
     * 报警过滤处理 抽取的私有方法
     *
     * @param deviceData 设备物模型数据
     */
    private void alertFilter(DeviceData deviceData) {
        // 查询该物模型下的全部报警规则 (根据productKey,functionid,status)
        List<AlertRule> alertRuleList = this.list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
        );
        // 判空
        if (CollectionUtils.isEmpty(alertRuleList)) {
            return;
        }
        // 遍历每一条规则并进行校验
        alertRuleList.forEach(alertRule -> {
            deviceDataAlarmHandle(alertRule, deviceData);
        });
    }

    /**
     * 设备物模型报警规则校验
     *
     * @param alertRule  报警规则
     * @param deviceData 设备物模型数据
     */
    private void deviceDataAlarmHandle(AlertRule alertRule, DeviceData deviceData) {
        // 1. 判断上报时间是否在规则生效时间内
        // 报警规则生效时间 (00:00:00~23:59:59)
        String alertEffectivePeriod = alertRule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
//        LocalTime alarmTime = LocalTime.parse(deviceData.getAlarmTime().toString());
        LocalDateTime alarmDateTime = LocalDateTime.parse(deviceData.getAlarmTime().toString());
        LocalTime alarmTime = alarmDateTime.toLocalTime();
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            return;
        }

        // 2. 判断数据是否达到报警阈值
        String iotId = deviceData.getIotId();
        // 设置redis-报警触发次数的key
        String triggerCountKey = Constants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        Long alertRuleValue = alertRule.getValue();
        String operator = alertRule.getOperator();
        Double dateValue = Double.valueOf(deviceData.getDataValue());
        int compare = NumberUtil.compare(dateValue, alertRuleValue); // x,y x<y 返回值<0 ,x>y 返回值>0  ,x=y 返回值0

        if ((compare >= 0 && operator.equals(">=")) || (compare < 0 && operator.equals("<"))) {
            // 达到报警阈值
            log.warn("当前上报的物模型数据达到报警阈值");
        } else {
            // 未达到报警阈值
            log.warn("当前上报的物模型数据没有达到报警阈值");
            // 删除redis报警触发次数
            redisTemplate.delete(triggerCountKey);
            return;
        }

        // 3. 判断是否处于沉默周期
        String silentKey = Constants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String silentData = (String) redisTemplate.opsForValue().get(silentKey);

        if (StringUtils.isNotEmpty(silentData)) {
            // 沉默周期存在,则说明在沉默周期内,不报警
            return;
        }

        // 4. 判断持续周期
        // 4.1 从redis中获取报警触发次数
        String triggerCountStr = (String) redisTemplate.opsForValue().get(triggerCountKey);
        // 4.2 计算新的报警次数
        int count = StringUtils.isEmpty(triggerCountStr) ? 1 : Integer.parseInt(triggerCountStr) + 1;
        // 4.3 报警次数是否等于持续周期
        if (ObjectUtil.notEqual(count, alertRule.getDuration())) {
            // 不满足,更新redis报警触发次数 ,并返回
            redisTemplate.opsForValue().set(triggerCountKey, String.valueOf(count));
            return;
        }
        // 5. 校验全部通过,进行报警
        // 5.1 删除redis报警触发次数,添加redis沉默周期
        redisTemplate.delete(triggerCountKey);
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        // 5.2 找到对应员工id集合
        List<Long> userIds = new ArrayList<>();
        // 5.2.1 如果是老人异常数据,找对应护理员
        if (deviceData.getLocationType() == 0) {
            // 如果是移动设备
            userIds = deviceMapper.selectNurseIdsByIotIdWithElder(iotId);
        } else if (deviceData.getLocationType() == 1 && deviceData.getPhysicalLocationType() == 2) {
            // 如果是固定设备(床位)
            userIds = deviceMapper.selectNurseIdsByIotIdWithBed(iotId);
        }
        // 5.2.2 如果是设备异常数据,找维修工
        if (deviceData.getLocationType() == 1 && deviceData.getPhysicalLocationType() == 1){
            userIds = userRoleMapper.selectUserIdByRoleName("维修工");
        }
        // 5.2.3 两张情况都需要通知 超级管理员
        List<Long> adminIds = userRoleMapper.selectUserIdByRoleName("超级管理员");
        // 合并ids
        Collection<Long> allIds = CollUtil.addAll(userIds, adminIds);
        // 去重
        allIds = CollUtil.distinct(allIds);

        // 6. 保存报警数据
        List<AlertData> alertDataList = insertAlertData(allIds, alertRule, deviceData);

        // websocket 推送报警信息
        websocketNotity(alertDataList.get(0), alertRule, allIds);
    }

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * websocket 推送报警信息
     *
     * @param alertData 报警数据
     * @param alertRule 报警规则
     * @param allIds    员工id集合
     */
    private void websocketNotity(AlertData alertData, AlertRule alertRule, Collection<Long> allIds) {
        // 属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1); // 0解除报警 1报警
        // 向指定的人推送信息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, allIds);
    }

    /**
     * 保存报警数据
     *
     * @param allIds     员工id集合
     * @param alertRule  报警规则
     * @param deviceData 设备物模型数据
     */
    private List<AlertData> insertAlertData(Collection<Long> allIds, AlertRule alertRule, DeviceData deviceData) {
        // 对象拷贝(deviceData->alertData)
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setStatus(0); // 待处理
        alertData.setType(alertRule.getAlertDataType()); // 0:老人异常数据,1:设备异常数据
        // 报警原因,格式:功能名称+运算符+阈值+持续周期
        String alertReason = alertRule.getFunctionName() + alertRule.getOperator() + alertRule.getValue()
                + ",持续" + alertRule.getDuration() + "个周期就报警";
        alertData.setAlertReason(alertReason);
        // 遍历allIds,构建存入数据库需要的集合对象(单独设置接收人id(userId))
        List<AlertData> alertDataList = allIds.stream().map(userId -> {
            AlertData dbalertData = BeanUtil.toBean(alertData, AlertData.class);
            dbalertData.setId(null);
            dbalertData.setUserId(userId);
            return dbalertData;
        }).collect(Collectors.toList()); //toList()
        // 批量保存
        alertDataService.saveBatch(alertDataList);
        return alertDataList;
    }

}
